<?php

namespace App\Kuafu\Bak\Command;

use App\Kuafu\Common\Service\SeparateService;
use App\Library\FeiShu\SendFs;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Kuafu\GeneralFs\BuildFs;

class DelOrderMonthCommand extends Command
{
    protected $signature = 'bak:del-order-month {bakMonth}';

    protected $description = '每月删除订单数据';


    public function handle()
    {
//        $bakMonth = (string)$this->argument('bakMonth'); // 202301

//        $this->doHandle('202301');
//        $this->doHandle('202302');
//        $this->doHandle('202303');
//        $this->doHandle('202304');
//        $this->doHandle('202305');
//        $this->doHandle('202306');
//        $this->doHandle('202307');
//        $this->doHandle('202308');
//        $this->doHandle('202309');
//        $this->doHandle('202310');
//        $this->doHandle('202311');
        $this->doHandle('202312');
    }

    /**
     * 删数据
     *
     * @param string $bakMonth
     * @return void
     * @throws \Exception
     */
    public function doHandle(string $bakMonth)
    {
        if (!$bakMonth) {
            dd('请输入删除月份');
        }

        $startSeconds = time();

        $this->info('开始ing');

        // 删除数据
        $allTables    = BakOrderMonthCommand::getBakTables();
        $delTotalRows = 0;
        foreach ($allTables as $db => $tables) {
            $this->info("开始删除{$db}库");

            foreach ($tables as $table) {
                $table        = ltrim($table, 'kf_');
                $delRows      = $this->del($db, $table, $bakMonth);
                $delTotalRows += $delRows;
            }
        }

        $this->info('结束删除');

        $useSeconds = time() - $startSeconds;

        $content = "执行耗时：{$useSeconds}秒";

        // 尝试更新隔断日期
        $t              = strtotime("+1 month {$bakMonth}01");
        $updateSeparate = SeparateService::updateSeparateTime($t);
        if ($updateSeparate) {
            $content .= ";更新隔断日期为：" . date('Y-m-d', $t);
        }

        // 发送消息通知
        BuildFs::newRobot(SendFs::ROBOT_INTERNAL)
               ->setTitleContent($bakMonth . '数据删除成功', $content . ' 共' . $delTotalRows . '条记录')
               ->send();
    }

    /**
     * 删除数据
     * @param string $db
     * @param string $table
     * @param string $bakMonth
     * @return int
     */
    private function del(string $db, string $table, string $bakMonth): int
    {
        $loopTotalCount = 0;
        for ($i = 0; $i <= 99; $i++) {
            $tableName = $table . str_pad($i, 3, 0, STR_PAD_LEFT);

            $this->info("开始删除{$tableName}");

            // start/endTime
            $startTime = strtotime($bakMonth . '01');
            $endTime   = strtotime("+1 month {$bakMonth}01");

            // 拉对应时间的数据 - $day 天
            $totalCount = DB::connection($db)
                            ->table($tableName)
                            ->where('createdAt', '>=', $startTime)
                            ->where('createdAt', '<=', $endTime)
                            ->count();

            $this->info("共计: {$totalCount}条");
            $loopTotalCount += $totalCount;

            while ($totalCount > 0) {
                $affectRow  = DB::connection($db)
                                ->table($tableName)
                                ->where('createdAt', '>=', $startTime)
                                ->where('createdAt', '<=', $endTime)
                                ->limit(1000)
                                ->delete();
                $totalCount -= $affectRow;

                $this->info("剩余{$totalCount}条");
//                sleep(1);

            }

            DB::connection($db)->statement("ALTER TABLE kf_{$tableName} ENGINE=InnoDB");
            DB::connection($db)->statement("ANALYZE TABLE kf_{$tableName};");

            $this->info("{$tableName}删除完成");
        }

        return $loopTotalCount;


    }
}
